import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { createSelector } from '@reduxjs/toolkit';
import { User, LoginRequest } from '../../types';
import AuthService from '../../services/authService';
import { PermissionManager } from '../../utils/permissions';

// 认证状态接口
interface AuthState {
  user: User | null;
  token: string | null;
  permissions: string[];
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
  loginLoading: boolean;
  logoutLoading: boolean;
}

// 初始状态
const storedPermissions = AuthService.getStoredPermissions() || [];
const initialState: AuthState = {
  user: AuthService.getStoredUser(),
  token: AuthService.getAuthToken(),
  permissions: storedPermissions,
  isAuthenticated: AuthService.isLoggedIn(),
  loading: false,
  error: null,
  loginLoading: false,
  logoutLoading: false,
};

// 异步actions

// 登录
export const login = createAsyncThunk(
  'auth/login',
  async (credentials: LoginRequest, { rejectWithValue }) => {
    try {
      const response = await AuthService.login(credentials);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.message || '登录失败');
    }
  }
);

// 登出
export const logout = createAsyncThunk(
  'auth/logout',
  async (_, { rejectWithValue }) => {
    try {
      await AuthService.logout();
    } catch (error: any) {
      return rejectWithValue(error.message || '登出失败');
    }
  }
);

// 获取当前用户信息
export const getCurrentUser = createAsyncThunk(
  'auth/getCurrentUser',
  async (_, { rejectWithValue }) => {
    try {
      const user = await AuthService.getCurrentUser();
      return user;
    } catch (error: any) {
      return rejectWithValue(error.message || '获取用户信息失败');
    }
  }
);

// 刷新token
export const refreshToken = createAsyncThunk(
  'auth/refreshToken',
  async (_, { rejectWithValue }) => {
    try {
      const token = await AuthService.refreshToken();
      return token;
    } catch (error: any) {
      return rejectWithValue(error.message || '刷新token失败');
    }
  }
);

// 修改密码
export const changePassword = createAsyncThunk(
  'auth/changePassword',
  async (data: { oldPassword: string; newPassword: string }, { rejectWithValue }) => {
    try {
      await AuthService.changePassword(data);
      return '密码修改成功';
    } catch (error: any) {
      return rejectWithValue(error.message || '密码修改失败');
    }
  }
);

// 验证token
export const validateToken = createAsyncThunk(
  'auth/validateToken',
  async (_, { rejectWithValue }) => {
    try {
      const isValid = await AuthService.validateToken();
      return isValid;
    } catch (error: any) {
      return rejectWithValue(error.message || 'Token验证失败');
    }
  }
);

// 创建slice
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    // 清除错误
    clearError: (state) => {
      state.error = null;
    },

    // 设置权限
    setPermissions: (state, action: PayloadAction<string[]>) => {
      state.permissions = action.payload;
    },

    // 更新用户信息
    updateUser: (state, action: PayloadAction<Partial<User>>) => {
      if (state.user) {
        state.user = { ...state.user, ...action.payload };
        localStorage.setItem('admin_user', JSON.stringify(state.user));
      }
    },

    // 重置状态
    resetAuth: (state) => {
      state.user = null;
      state.token = null;
      state.permissions = [];
      state.isAuthenticated = false;
      state.loading = false;
      state.error = null;
      state.loginLoading = false;
      state.logoutLoading = false;
    },
  },
  extraReducers: (builder) => {
    // 登录
    builder
      .addCase(login.pending, (state) => {
        state.loginLoading = true;
        state.error = null;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.loginLoading = false;
        state.user = action.payload.user;
        state.token = action.payload.token;
        state.permissions = action.payload.permissions;
        state.isAuthenticated = true;
        state.error = null;
      })
      .addCase(login.rejected, (state, action) => {
        state.loginLoading = false;
        state.error = action.payload as string;
        state.isAuthenticated = false;
      });

    // 登出
    builder
      .addCase(logout.pending, (state) => {
        state.logoutLoading = true;
      })
      .addCase(logout.fulfilled, (state) => {
        state.logoutLoading = false;
        state.user = null;
        state.token = null;
        state.permissions = [];
        state.isAuthenticated = false;
        state.error = null;
      })
      .addCase(logout.rejected, (state, action) => {
        state.logoutLoading = false;
        state.error = action.payload as string;
        // 即使登出失败，也清除本地状态
        state.user = null;
        state.token = null;
        state.permissions = [];
        state.isAuthenticated = false;
      });

    // 获取当前用户信息
    builder
      .addCase(getCurrentUser.pending, (state) => {
        state.loading = true;
      })
      .addCase(getCurrentUser.fulfilled, (state, action) => {
        state.loading = false;
        state.user = action.payload;
        state.isAuthenticated = true;
        localStorage.setItem('admin_user', JSON.stringify(action.payload));
      })
      .addCase(getCurrentUser.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
        // 如果获取用户信息失败，可能token已过期
        state.isAuthenticated = false;
      });

    // 刷新token
    builder
      .addCase(refreshToken.pending, (state) => {
        state.loading = true;
      })
      .addCase(refreshToken.fulfilled, (state, action) => {
        state.loading = false;
        state.token = action.payload;
      })
      .addCase(refreshToken.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
        // token刷新失败，需要重新登录
        state.isAuthenticated = false;
      });

    // 修改密码
    builder
      .addCase(changePassword.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(changePassword.fulfilled, (state) => {
        state.loading = false;
      })
      .addCase(changePassword.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 验证token
    builder
      .addCase(validateToken.pending, (state) => {
        state.loading = true;
      })
      .addCase(validateToken.fulfilled, (state, action) => {
        state.loading = false;
        state.isAuthenticated = action.payload;
      })
      .addCase(validateToken.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
        state.isAuthenticated = false;
      });
  },
});

// 导出actions
export const { clearError, setPermissions, updateUser, resetAuth } = authSlice.actions;

// 基础选择器
export const selectAuth = (state: { auth: AuthState }) => state.auth;
export const selectUser = (state: { auth: AuthState }) => state.auth.user;
export const selectIsAuthenticated = (state: { auth: AuthState }) => state.auth.isAuthenticated;
export const selectPermissions = (state: { auth: AuthState }) => state.auth.permissions;
export const selectAuthLoading = (state: { auth: AuthState }) => state.auth.loading;
export const selectAuthError = (state: { auth: AuthState }) => state.auth.error;
export const selectLoginLoading = (state: { auth: AuthState }) => state.auth.loginLoading;

// 使用 createSelector 创建 memoized 选择器，避免重复创建实例
export const selectPermissionManager = createSelector(
  [selectPermissions],
  (permissions) => {
    if (!permissions || permissions.length === 0) {
      return null;
    }
    return new PermissionManager(permissions);
  }
);

// 导出reducer
export default authSlice.reducer;
